'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 和好友战斗
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var Code = require('../../../../consts/code');
var atkData = require('../../../../libs/war/atkData');
var battleData = require('../../../../libs/war/battleData');
var PlayerManager = require('../../../../libs/playerManager');
var taskService = require('../../../../services/taskService');
var activityService = require('../../../../services/activityService.js');
var actType = require('../../../../consts/activityType.js');

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var rival_role_id = msg.rival_role_id;
    if (!rival_role_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var atk_data;
    var def_data;
    var player_manager = new PlayerManager(role_id);

    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['rebel', 'role', 'bag', 'build', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'],
                    cb);
            },
            function (cb) {
                // 进行一次防守任务统计
                taskService.addBattleDefense(player_manager);
                activityService.push(role_id, actType.DEFENSE, player_manager);

                // 被攻击方数据
                _getDef(rival_role_id, cb);
            },
            function (data, cb) {
                def_data = data;

                if (!def_data) {
                    return next(null, {
                        code: Code.BATTLE_DEF_NOT_EXIST
                    });
                }

                // 我方数据
                _getAtk(role_id, cb);
            },
            function (data, cb) {
                atk_data = data;
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    record_id: 0,
                    atk: atk_data,
                    def: def_data
                }
            });
        }
    );
};

/**
 * 获取攻击方数据
 * @return {[type]} [description]
 */
var _getAtk = function (role_id, cb) {
    atkData.getData(role_id, cb);
};

/**
 * 获取防守方数据
 * @return {[type]} [description]
 */
var _getDef = function (role_id, cb) {
    battleData.getData(role_id, cb);
};
